/*******************************************************************************
 * Copyright (c) 2008 Sylvain Sicard.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Sylvain Sicard - initial API and implementation
 ******************************************************************************/
package fr.jade.console.cmd;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import fr.jade.console.core.AbstractCommand;
import fr.jade.console.core.Command;
import fr.jade.console.core.Environment;
import fr.jade.console.core.JTerm;

/**
 * @author Sylvain Sicard

 */
public class Source extends AbstractCommand implements Command{

  public String getDescription(){
    return "execute a JTerm script file";
  }
  
  public String getHelp(){
    return "source <script file name>";
  }
  
  public String getName() {
    return "source";
  }
  
	public Object execute (String[] args, Environment env) throws Throwable {
		JTerm sh = (JTerm)env.getEnvVar("shell");
		try{
		  File sourceFile = new File(args[1]);
		  InputStream is = null;
		  if(sourceFile.exists()){
		     is = new FileInputStream(sourceFile);
		  }else{
		    is = getClass().getResourceAsStream("/"+args[1]);
		  }
		  if(is == null){
		    System.out.println(args[1]+" not found neither in classpath nor in the file system");
		  }else{
  			BufferedReader in = new BufferedReader(new InputStreamReader(is));
  			String cmdLine;
  			while( (cmdLine = in.readLine()) != null){
  				System.out.println(cmdLine);
  				sh.evaluateCmd(cmdLine);
  			}
		  }
		}catch(IOException e){
      System.out.println("Load # Eror while reading "+ args[1]);
    }
		return null;
	}
}
